<template>
    <div>
        <div class="addFileDiv">
            <div>
                <Input v-model="searchContent" placeholder="请输入文件名或备注内容" @keyup.enter.native="searchFile()" style="width: 60%"/>
                <Button type="primary" size="small" @click="searchFile()" style="background-color: #CDC673; border: 0px;">
                    <img src="~@/assets/icon/search.png" width="30px" height="30px">
                </Button>
            </div>
            <!--<Button type="primary" size="small" @click="addManager()">加入管理</Button>-->
            <div style="margin-top: 10px">
                <Button type="default" ghost size="small" @click="selectFile()">选择文件</Button>
                <span style="color: #FFF; cursor: pointer; font-size: 12px" @click="showFolderExplain(1)">？</span>
                &nbsp;&nbsp;&nbsp;&nbsp;
                <Button type="default" ghost size="small" @click="selectFolder()">选择文件夹</Button>
                <span style="color: #FFF; cursor: pointer; font-size: 12px" @click="showFolderExplain(2)">？</span>
            </div>
        </div>

        <div class="fileContent">
            <div style="width: 100%;text-align: right;margin-bottom: 6px; color: #FFF">
                <span>共{{fileData.length}}个文件</span>
                <br>
            </div>
            <Table @on-row-dblclick="openFile" height="400" :columns="columns" :data="fileData"></Table>
        </div>
        <Modal
                v-model="editModal"
                title="文件修改">
            <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80">
                <FormItem label="编号">
                    <span>{{formValidate.id}}</span>
                </FormItem>
                <FormItem label="文件名称" prop="file_name">
                    <Input v-model="formValidate.file_name" placeholder="请输入文件名称"></Input>
                </FormItem>
                <FormItem label="文件路径" prop="file_path">
                    <Input v-model="formValidate.file_path" placeholder="请输入文件路径"></Input>
                </FormItem>
                <FormItem label="后缀">
                    <Input v-model="formValidate.suffix" placeholder="请输入文件后缀"></Input>
                </FormItem>
                <FormItem label="备注">
                    <textarea v-model="formValidate.remark" placeholder="请输入文件备注" style="width: 100%"></textarea>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" size="large" @click="editCancel">取消</Button>
                <Button type="primary" size="large" @click="editSave">确定</Button>
            </div>
        </Modal>

        <Modal
                v-model="addFileModal"
                title="新增文件">
            <Form :label-width="80">
                <FormItem label="文件名称" prop="file_name">
                    <textarea name="filePath" v-model="filePath" style="width: 90%"></textarea>
                </FormItem>
                <FormItem label="备注" prop="file_name">
                    <textarea name="remark" v-model="addRemark" style="width: 90%"></textarea>
                </FormItem>
            </Form>
            <div slot="footer">
                <Button type="text" size="large" @click="closeAddModel">取消</Button>
                <Button type="primary" size="large" @click="addManager">确定</Button>
            </div>
        </Modal>
    </div>
</template>
<script>
  import {getDB} from '../js/dbUtil'
  import {parseFilePath} from '../js/fileUtil'
  import $ from 'jquery'

  const {dialog} = require('electron').remote
  const Electron = require('electron')
  const remote = Electron.remote
  const Menu = remote.Menu
  const MenuItem = remote.MenuItem
  const { shell } = require('electron').remote
  const path = require('path')
  const fs = require('fs')

  let that
  require('electron').ipcRenderer.on('initPageMenu', (event, message) => {
    console.log(message) // Prints 'whoooooooh!'，这里的message是object类型
    // that.initMenu()
    console.info(that)
  })

  function formatToString (data) {
    let result = ''
    for (let i = 0; i < data.length; i++) {
      if (i !== data.length - 1) {
        result += data[i] + ','
      } else {
        result += data[i]
      }
    }
    return result
  }

  export default {
    name: 'FileManger',
    components: {},
    data () {
      return {
        filePath: '',
        addRemark: '',
        searchContent: '',
        editModal: false,
        addFileModal: false,
        filePathArray: [],
        toOpenPath: '',
        formValidate: {
          id: '',
          file_name: '',
          file_path: '',
          suffix: '',
          remark: ''
        },
        ruleValidate: {
          file_name: [
            {required: true, message: '文件名不能为空', trigger: 'blur'}
          ],
          file_path: [
            {required: true, message: '文件路径不能为空', trigger: 'blur'}
          ]
        },
        columns: [
          {
            title: '编号',
            key: 'id',
            width: '60px'
          },
          {
            title: '文件名',
            key: 'file_name',
            width: '200px'
          },
          {
            title: '路径',
            key: 'file_path'
          },
          {
            title: '格式',
            key: 'suffix',
            width: '60px'
          },
          {
            title: '收录时间',
            key: 'create_time',
            width: '150px'
          },
          {
            title: '操作',
            key: 'action',
            fixed: 'right',
            width: 160,
            render: (h, params) => {
              return h('div', [
                h('Button', {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      this.showDetail(params.row)
                    }
                  }
                }, '详情'),
                h('Button', {
                  props: {
                    type: 'text',
                    size: 'small'
                  },
                  on: {
                    click: () => {
                      console.info('编辑:', params.row)
                      this.toEdit(params.row)
                    }
                  }
                }, '编辑'),

                h('Poptip', {
                  props: {
                    title: '您确定要删除这条数据吗?',
                    transfer: true,
                    confirm: true,
                    placement: 'top-end'
                  },
                  on: {
                    'on-ok': () => {
                      this.remove(params.row.id)
                    }
                  }
                }, [
                  h('Button', {
                    style: {
                      marginLeft: '2px'
                    },
                    props: {
                      type: 'text',
                      size: 'small'
                    }
                  }, '删除')
                ])
              ])
            }
          }
        ],
        fileData: []
      }
    },
    created () {
      console.info('初始化文件管理')
      let loadFlag = this.$store.state.menuFirstLoad
      if (loadFlag === 'no') {
        this.$store.state.menuFirstLoad = 'yes'
        this.initMenu()
      }
      this.loadData()
    },
    activated () {
      that = this
      let id = this.$route.query.id
      console.info('activated传过来的id为：', id)
      if (id) {
        this.loadOneData(id)
      }
    },
    methods: {
      // 展示详情
      showDetail (param) {
        this.$Modal.info({
          title: '文件信息',
          content: `编号：${param.id}<br>文件名：${param.file_name}<br>路径：${param.file_path}<br>格式：${param.suffix}<br>收录时间：${param.create_time}<br>备注：${param.remark}`
        })
      },
      openFile (e) {
        shell.openItem(e.file_path)
      },
      showFolderExplain (flag) {
        console.info('flag', flag)
        let title = '选择文件'
        let content = '选择单个文件，选择文件后会弹出一个弹出框，用户在确认信息后可以进行保存'
        if (flag === 2) {
          title = '选择文件夹'
          content = '选择一个文件夹，系统会自动递归遍历下面的文件以及子文件夹内的文件，遍历完后显示在弹出框中，用户在确认信息后可以进行保存'
        }
        this.$Modal.info({
          title: title,
          content: content
        })
      },
      // 展示到修改界面
      toEdit (params) {
        this.editModal = true
        this.formValidate = params
      },
      remove (id) {
        let db = getDB()
        let that = this
        db.run('delete from t_file where id = $id', {
          $id: id
        }, function (err) {
          if (err) {
            that.$Message.error('删除失败')
            throw err
          } else {
            that.$Message.success('删除成功')
            that.loadData()
          }
        })
      },
      // 修改保存
      editSave () {
        let that = this
        this.$refs['formValidate'].validate(valid => {
          if (valid) {
            let db = getDB()
            db.all(`select id, file_name, file_path, suffix, create_time, remark from t_file where file_path = $file_path and id != $id`, {
              $file_path: this.formValidate.file_path,
              $id: this.formValidate.id
            }, function (err, row) {
              // console.info(sql)
              if (err) throw err
              else {
                console.log('查询结果数量', row.length)
                if (row.length === 0) {
                  db.run('update t_file set file_name = $file_name, file_path = $file_path, suffix = $suffix, remark = $remark where id = $id', {
                    $file_name: that.formValidate.file_name,
                    $file_path: that.formValidate.file_path,
                    $suffix: that.formValidate.suffix,
                    $remark: that.formValidate.remark,
                    $id: that.formValidate.id
                  }, function (err) {
                    if (err) throw err
                  })
                  that.editModal = false
                  that.$Message.success('修改成功')
                } else {
                  console.info('修改失败，与其他文件目录相同')
                  that.$Message.error('修改失败，与其他文件目录相同')
                }
              }
            })
          }
        })
      },
      editCancel () {
        this.editModal = false
      },
      closeAddModel () {
        this.addFileModal = false
      },
      searchFile () {
        console.info('搜索内容', this.searchContent)
        this.loadData()
      },
      selectFile: function () {
        console.info('selectFile')
        let that = this
        dialog.showOpenDialog({
          title: '选择文件', // 对话框的标题
          properties: ['openFile', 'multiSelections'], // 打开文件夹，默认打开文件，multiSelections可以多选
          filters: [
            {
              // name: 'img',
              // extensions: ['jpg', 'png'] // 只允许 jpg 和 png 格式的文件
            }
          ],
          buttonLabel: '选择文件' // 自定义按钮文本显示内容
        }, function (data) {
          console.log(data)
          that.filePathArray = data
          that.filePath = formatToString(data)
          if (data.length > 0) {
            that.addFileModal = true
          }
        })
      },
      selectFolder: function () {
        console.info('selectFolder')
        let that = this
        dialog.showOpenDialog({
          title: '选择文件夹', // 对话框的标题
          properties: ['openDirectory', 'multiSelections'], // 打开文件夹，默认打开文件，multiSelections可以多选
          filters: [
            {}
          ],
          buttonLabel: '选择文件夹' // 自定义按钮文本显示内容
        }, function (data) {
          console.log(data)
          that.filePathArray = data
          // that.filePath = formatToString(data)
          if (data.length > 0) {
            that.addFileModal = true
          }
          let tempData = []
          for (let i = 0; i < data.length; i++) {
            console.info('开始遍历文件夹', data[i])
            that.mapDir(data[i], tempData)
          }
          that.filePathArray = tempData
          that.filePath = formatToString(that.filePathArray)
        })
      },
      mapDir: function (dir, data) {
        console.info('正在遍历', dir)
        let files = fs.readdirSync(dir)
        files.forEach((filename, index) => {
          let pathname = path.join(dir, filename)
          console.info('遍历子文件', pathname)
          let stats = fs.statSync(pathname)
          if (stats.isDirectory()) {
            this.mapDir(pathname, data)
          } else if (stats.isFile()) {
            data.push(pathname)
          }
        })
      },
      addManager: function () {
        let fs = require('fs')
        let that = this
        let saveFileArray = this.filePath.split(',')
        console.info('文件数量', saveFileArray.length)
        let db = getDB()
        for (let i = 0; i < saveFileArray.length; i++) {
          console.info('file', saveFileArray[i])
          let path = saveFileArray[i]
          if (path === '') {
            this.$Notice.config({
              top: 130,
              duration: 3
            })
            this.$Notice.error({
              title: '错误',
              desc: '文件不能为空 '
            })
            return
          }
          fs.stat(path, function (err, stat) {
            if (err) {
              console.error(err)
              that.$Notice.config({
                top: 130,
                duration: 3
              })
              that.$Notice.error({
                title: '错误',
                desc: '文件处理异常，请检查文件是否有效 '
              })
              throw err
            }
            // 文件处理
            if (stat.isFile()) {
              console.info('是文件，保存')
              let fileObj = parseFilePath(path)
              console.info('fileObj:', fileObj)

              db.all(`select id, file_name, file_path, suffix, create_time, remark from t_file where file_path = $file_path`, {
                $file_path: path
              }, function (err, row) {
                // console.info(sql)
                if (err) throw err
                else {
                  console.log('查询结果数量', row.length)
                  if (row.length === 0) {
                    db.run('insert into t_file(file_name, file_path, suffix, remark) values ($file_name, $file_path, $suffix, $remark)', {
                      $file_name: fileObj.file_name,
                      $file_path: path,
                      $suffix: fileObj.suffix,
                      $remark: that.addRemark
                    }, function (err) {
                      if (err) {
                        that.$Message.error('新增失败')
                        throw err
                      } else {
                        that.$Message.success('新增成功')
                        that.filePath = ''
                        that.addRemark = ''
                      }
                    })
                  } else {
                    console.info('新增失败，与其他文件目录相同')
                    that.$Message.error('新增失败，与其他文件目录相同')
                  }
                }
              })
            }
            // 文件夹处理
            if (stat.isDirectory()) {
              console.info('是文件夹，继续遍历')
            }
          })
        }
        that.loadData()
        this.addFileModal = false
      },
      loadData: function () {
        let db = getDB()
        let that = this
        let sql = `select id, file_name, file_path, suffix, create_time, remark from t_file order by create_time desc`
        if (this.searchContent) {
          sql = `select id, file_name, file_path, suffix, create_time, remark from t_file where (file_name like '%${this.searchContent}%' or remark like '%${this.searchContent}%') order by create_time desc`
        }
        db.all(sql, function (err, row) {
          // console.info(sql)
          if (err) throw err
          else {
            console.log('查询结果数量', row.length)
            that.fileData = row
            if (row.length === 0) {
              that.$Message.warning('哎呀！什么都没查到！')
            }
            console.info('查询数据为', that.fileData)
          }
        })
      },
      loadOneData: function (id) {
        let db = getDB()
        let that = this
        let sql = `select id, file_name, file_path, suffix, create_time, remark from t_file where id = ${id}`
        db.all(sql, function (err, row) {
          // console.info(sql)
          if (err) throw err
          else {
            console.log('查询结果数量', row.length)
            that.fileData = row
            console.info('查询数据为', that.fileData)
          }
        })
      },
      initMenu () { // eslint-disable-line
        let that = this
        console.info('初始化菜单', that)
        const menu = new Menu()
        menu.append(new MenuItem({
          label: '打开',
          role: 'openFile',
          click: function (data) {
            console.info('打开文件abc', that.toOpenPath)
            shell.openItem(that.toOpenPath)
          }
        }))
        menu.append(new MenuItem({
          label: '打开路径',
          click: function (data) {
            console.info('打开路径abc', that.toOpenPath)
            shell.showItemInFolder(that.toOpenPath)
          }
        }))

        document.addEventListener('contextmenu', (e) => {
          e.preventDefault()
          console.info('使用that', that)
          if (this.isFileRecord(e.target, that)) {
            menu.popup(remote.getCurrentWindow())
          }
        }, false)
      },
      isFileRecord (e, that) {
        if (e) {
          if (e.tagName === 'TR') {
            console.info('判断对象:', e)
            console.info('打印e对象', $(e).find('td').eq(2).find('span').text())
            that.toOpenPath = $(e).find('td').eq(2).find('span').text()
            return true
          } else {
            // 递归查询父节点
            return this.isFileRecord(e.parentNode, that)
          }
        } else {
          return false
        }
        // 为input标签或者contenteditable属性为true
      }
    }
  }
</script>

<style scoped>
    .addFileDiv {
        width: 100%;
        margin-top: 30px;
        margin-left: auto;
        margin-right: auto;
        text-align: center;
    }
    .fileContent {
        margin-top: 0px;
        width: 97%;
        text-align: center;
        margin-left: auto;
        margin-right: auto;
    }
</style>
